package com.tg.app.activity.device.settings;

import static com.tg.app.activity.device.DeviceSettingHelper.RESET_DEVICE_ACTIVITY;
import static com.tg.app.activity.device.DeviceSettingsActivity.ACTION_DEVICE_SETTINGS;
import static com.tg.app.activity.device.DeviceSettingsActivity.CHANGE_DEVICE_WIFI_ACTIVITY;
import static com.tg.app.activity.device.DeviceSettingsActivity.EXT_DEVICE_INFO;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;

import com.alibaba.fastjson.JSONObject;
import com.appbase.custom.constant.CommonConstants;
import com.appbase.custom.constant.DeviceStateConstants;
import com.demo.view.SettingItemSwitchView;
import com.demo.view.SettingItemTextView;
import com.tange.module.device.feature.DeviceFeatureObjectBox;
import com.tange.module.device.feature.DeviceFeature_;
import com.tange.module.socket.SocketIoConstants;
import com.tg.app.R;
import com.tg.app.TGDevice;
import com.tg.app.activity.base.DeviceSettingsBaseActivity;
import com.tg.app.activity.device.DeviceSettingHelper;
import com.tange.module.device.feature.DeviceFeature;
import com.tg.app.camera.AVIOCTRLDEFs;
import com.tg.app.camera.Camera;
import com.tange.module.camera.hub.CameraHub;
import com.tg.app.camera.P2PReport;
import com.tg.app.helper.DeviceHelper;
import com.tg.app.helper.TGGlobalConfigHelper;
import com.tg.app.util.LogUtils;
import com.tg.app.util.ObjectBoxUtil;
import com.tg.app.util.UriUtil;
import com.tange.base.toolkit.DateUtil;
import com.tange.base.toolkit.NetworkUtil;
import com.tg.appcommon.android.Packet;
import com.tange.base.toolkit.StringUtils;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tange.base.toolkit.TGThreadPool;
import com.tg.appcommon.android.TGToast;
import com.tg.data.bean.DeviceItem;
import com.tg.data.bean.DeviceSettingsInfo;
import com.tg.data.bean.DeviceSettingsInfo_;
import com.tg.data.helper.DeviceTypeHelper;
import com.tg.data.http.entity.SMsgAVIoctrlIPCONFIGRespBean;
import com.tg.data.media.OnICameraListener;
import com.tange.core.backend.service.http.ClientObserver;
import com.tg.network.socket.http.TGHttp;

import java.util.HashMap;
import java.util.TimeZone;

import io.objectbox.Box;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class MoreSettingsActivity extends DeviceSettingsBaseActivity implements OnICameraListener{
    private DeviceSettingsInfo mDeviceSettingsInfo;
    private DeviceItem  mDevice;
    private Camera camera;
    private SettingItemSwitchView mSettingItemClose;
    private SettingItemTextView mSettingItemIPConfig;
    private SettingItemTextView mSettingItemTimeZone,mSettingItemTime;
    private static final String TAG = MoreSettingsActivity.class.getSimpleName();
    private final Handler handler = new Handler();
    private DeviceFeature deviceFeature;
    private SMsgAVIoctrlIPCONFIGRespBean mSMsgAVIoctrlIPCONFIGResp;
    private class DeviceSettingsBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (ACTION_DEVICE_SETTINGS.equals(intent.getAction())) {

                DeviceSettingsInfo rInfo = null;
                try {
                    rInfo = intent.getParcelableExtra(EXT_DEVICE_INFO);
                } catch (Exception ex) {}

                if (rInfo != null) {
                    rInfo.id = mDeviceSettingsInfo.id;
                    mDeviceSettingsInfo = rInfo;
                    updateSettings();
                }

                DeviceItem deviceItem = intent.getParcelableExtra(CommonConstants.EXT_DEVICE_ITEM);
                if (deviceItem != null){
                    mDevice = deviceItem;
                    mDeviceSettingsInfo.deviceStatus = mDevice.is_open;
                }
            }
        }
    }

    @Override
    public boolean shouldSetStatusBarColor() {
        return true;
    }

    private void updateSettings() {
        if (deviceFeature != null) {
            Box<DeviceFeature> deviceFeatureBox = DeviceFeatureObjectBox.getDeviceFeature();
            assert deviceFeatureBox != null;
            deviceFeatureBox.put(deviceFeature);
        }
        if (mDeviceSettingsInfo != null) {
            Box<DeviceSettingsInfo> deviceSettingsInfoBox = ObjectBoxUtil.getDeviceSettingsInfo();
            mDeviceSettingsInfo.updated_at = System.currentTimeMillis();
            if (deviceSettingsInfoBox != null){
                deviceSettingsInfoBox.put(mDeviceSettingsInfo);
            }
        }
    }

    @Override
    public void receiveUpdateConnectStates(int state) {
        if (NetworkUtil.isNetworkConnected(TGApplicationBase.getApplication())){
            if (state == Camera.CONNECTION_STATE_CONNECTED) {
                getIpConfig();
            } else if (state == Camera.CONNECTION_STATE_DISCONNECTED || state == Camera.CONNECTION_STATE_CONNECT_FAILED) {
                if (mDeviceSettingsInfo != null) {
                    mDeviceSettingsInfo.deviceStatus = mDevice.is_open;
                }

                runOnUiThread(() -> setDeviceStatus(mDevice.is_open));
                handler.removeCallbacks(timeRunable);
                handler.post(timeRunable);
            }
        }
    }

    private void getIpConfig() {
        if (deviceFeature != null &&  deviceFeature.supportIpConfig){
            camera.sendIOCtrl(AVIOCTRLDEFs.TCI_CMD_GET_IPCONFIG_REQ, new byte[1]);
        }
    }

    @Override
    public void receiveIOCtrlData(int type, byte[] data) {
        if (type == AVIOCTRLDEFs.TCI_CMD_GET_IPCONFIG_RESP){
            TGLog.d("receiveIOCtrlData   ==============");
            mSMsgAVIoctrlIPCONFIGResp = SMsgAVIoctrlIPCONFIGRespBean.build(data);
            //0:手动配置; 1:自动配置;
            setIPConfig();

        } else if (type == AVIOCTRLDEFs.TCI_CMD_SET_COMMAND_RESP) {
            int command = Packet.byteArrayToInt_Little(data, 0);
            int result = Packet.byteArrayToInt_Little(data, 4);
            if (command == AVIOCTRLDEFs.TCL_CMD_SET_CAMERA_STATUS_REQ) {
                TGLog.d(TAG, "mDeviceSettingsInfo.deviceStatus=========result =" + result);
                if (result == 0) {
                    Intent intent = new Intent();
                    intent.setAction(SocketIoConstants.NOTIFY_DEVICE_STATUS);
                    JSONObject object = new JSONObject();
                    object.put("device_id", mDevice.id);
                    mDevice.is_open = mSettingItemClose.isChecked() ? DeviceStateConstants.DEVICE_OPEN : DeviceStateConstants.DEVICE_OFF;
                    TGLog.d(TAG, "mDeviceSettingsInfo.deviceStatus=========" + mDevice.is_open);

                    String type2 = SocketIoConstants.DEVICE_STATUS_OPEN;
                    if (mDeviceSettingsInfo != null) {
                        mDeviceSettingsInfo.deviceStatus = mDevice.is_open;
                    }
                    if (mDevice.is_open == DeviceStateConstants.DEVICE_OFF) {
                        type2 = SocketIoConstants.DEVICE_STATUS_SHUTDOWN;
                    }
                    object.put("type", type2);
                    intent.putExtra(SocketIoConstants.NOTIFY_KEY_DATA, object.toJSONString());
                    sendBroadcast(intent);

                    sendUpdateSettingBroadcast(mDeviceSettingsInfo, mDevice);
                } else {
                    TGThreadPool.executeOnUiThread(() -> {
                        mSettingItemClose.setChecked(!mSettingItemClose.isChecked());
                        TGToast.showToast(R.string.txt_network_anomaly);
                    });

                }
            }
        }
    }

    private void setIPConfig() {
        TGThreadPool.executeOnUiThread(() -> {
            if (mSMsgAVIoctrlIPCONFIGResp.bDhcpEnabled == 0){
                mSettingItemIPConfig.setContent(R.string.txt_manual_network_setting);
            }else{
                mSettingItemIPConfig.setContent(R.string.txt_auto_network_setting);
            }
        });

    }

    @Override
    protected void onSetupFailed() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_more_settings);
        hideActionBar();
        getIntentData();
        initDeviceSettingsInfo();
        initView();
        initRecerver();
        initData();
    }

    private void initDeviceSettingsInfo() {
        Box<DeviceSettingsInfo> deviceSettingsInfoBox = ObjectBoxUtil.getDeviceSettingsInfo();
        if (mDevice != null) {
            assert deviceSettingsInfoBox != null;
            DeviceSettingsInfo info = deviceSettingsInfoBox.query().equal(DeviceSettingsInfo_.uuid, mDevice.uuid).build().findFirst();
            if (info != null){
                mDeviceSettingsInfo = info;
            }
            if (mDeviceSettingsInfo == null) {
                mDeviceSettingsInfo = new DeviceSettingsInfo();
                updateInfo();
            }
            mDeviceSettingsInfo.deviceStatus = mDevice.is_open;
        }
    }

    private void updateInfo(){
        if (mDevice != null && mDeviceSettingsInfo != null) {
            mDeviceSettingsInfo.deviceID = mDevice.id;
            mDeviceSettingsInfo.uuid = mDevice.uuid;
            mDeviceSettingsInfo.online = (mDevice.is_online == DeviceStateConstants.DEVICE_ONLINE);
            mDeviceSettingsInfo.firmware_id = mDevice.firmware_id;
            mDeviceSettingsInfo.timezone = mDevice.timezone;

        }
    }

    private void getIntentData() {
        mDeviceSettingsInfo = getIntent().getParcelableExtra(EXT_DEVICE_INFO);
        camera = mDeviceSettingsInfo == null? null : CameraHub.getInstance().getCamera(mDeviceSettingsInfo.uuid);
        mDevice = getIntent().getParcelableExtra(CommonConstants.EXT_DEVICE_ITEM);
        Box<DeviceFeature> featureBox = DeviceFeatureObjectBox.getDeviceFeature();
        if (featureBox != null){
            String uid = mDeviceSettingsInfo != null? mDeviceSettingsInfo.uuid : null;
            if (StringUtils.isEmpty(uid)){
                uid = mDevice.uuid;
            }
            deviceFeature = featureBox.query().equal(DeviceFeature_.uuid, uid).build().findFirst();
        }
    }

    private void initRecerver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_DEVICE_SETTINGS);
        DeviceSettingsBroadcastReceiver receiver = new DeviceSettingsBroadcastReceiver();
        registerReceiver(receiver, intentFilter);
    }

    private void initCamera() {
        if (mDevice != null) {
            camera = CameraHub.getInstance().getCamera(mDevice.uuid);
            if (camera == null) {
                camera = CameraHub.getInstance().getCamera(DeviceItem.createBasicDevice(mDevice));
            }
        }
        if (camera != null) {
            camera.registerICameraListener(this);
        }
        if (camera != null && NetworkUtil.isNetworkConnected(TGApplicationBase.getApplication())){
            if (!camera.isShared && !DeviceHelper.is4GExpired(mDevice)) {
                if (!camera.isConnected()) {
                    camera.connect();
                }else{
                    getIpConfig();
                }
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mDeviceSettingsInfo != null) {
            setDeviceStatus(mDeviceSettingsInfo.deviceStatus);
        }
        Box<DeviceFeature> featureBox = DeviceFeatureObjectBox.getDeviceFeature();
        initCamera();
        if (camera != null) {
            if (featureBox != null){
                deviceFeature = featureBox.query().equal(DeviceFeature_.uuid, camera.uid).build().findFirst();
            }

            if (!camera.isShared) {
                camera.registerICameraListenerAndConnect(this);
            }
        }
        mSettingItemIPConfig.setVisibility(deviceFeature != null &&  deviceFeature.supportIpConfig ? View.VISIBLE : View.GONE);
    }

    private void setDeviceStatus(int deviceStatus) {
        if (mSettingItemClose != null) {
            mSettingItemClose.setChecked(deviceStatus == DeviceStateConstants.DEVICE_OPEN);
        }
    }

    private void initData() {
        setDeviceStatus(mDeviceSettingsInfo.deviceStatus);
        getDeviceInfo();
    }
    private void setTimeZoneText(){
        if (mDevice==null||TextUtils.isEmpty(mDevice.timezone))return;
        String zone =  DateUtil.getTimeZone();
        boolean isEmpty = TextUtils.isEmpty(mDevice.getCountry())||TextUtils.isEmpty(mDevice.getCity());
        if (mDevice.timezone.contains(zone)&&isEmpty){
            mSettingItemTimeZone.setContent(R.string.txt_phone_timezone_setting);
        }else {
            mSettingItemTimeZone.setContent(String.format("%s(%s)",mDevice.getCity(),mDevice.getCountry()));
        }
       TimeZone mTimeZone = DeviceHelper.getTimeZone(mDevice);
        String format = "yyyy/MM/dd HH:mm:ss";
       String time =  DateUtil.getTimeByZone(mTimeZone,format);
       if (!TextUtils.isEmpty(time)){
           mSettingItemTime.setContent(time);
       }

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (camera != null) {
            camera.unregisterICameraListener(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void setCloseCMD(int on) {
        if (camera != null) {
            camera.setCloseCMD(on);
        }
        if (mDevice != null){
            mDevice.is_open = on;
        }
        if (mDeviceSettingsInfo != null && mDevice != null) {
            mDeviceSettingsInfo.deviceStatus = mDevice.is_open;
        }

        sendUpdateSettingBroadcast(mDeviceSettingsInfo, mDevice);

    }

    Runnable timeRunable = new Runnable() {
        @Override
        public void run() {
            hideLoading();
            showToast(R.string.read_set_fail);
        }
    };


    @Override
    protected void initView() {
        backClickEvent();
        modifyToolBar(R.string.txt_more_setting);
        mSettingItemClose = findViewById(R.id.rl_settings_deivce_close);
        mSettingItemIPConfig = findViewById(R.id.rl_settings_network_service);
        mSettingItemTimeZone = findViewById(R.id.rl_settings_device_timezone);
        mSettingItemTime = findViewById(R.id.rl_settings_device_time);
        mSettingItemIPConfig.setVisibility(deviceFeature != null &&  deviceFeature.supportIpConfig ? View.VISIBLE : View.GONE);
        findViewById(R.id.rl_settings_change_device_wifi).setVisibility(showWIFI() ? View.VISIBLE : View.GONE);
        mSettingItemClose.setVisibility(deviceFeature != null && deviceFeature.supportCloseDevice? View.VISIBLE : View.GONE);
        setListener();
    }


    private void setListener() {
        mSettingItemClose.setOnClickListener(v -> {
            LogUtils.onEventClickByName("device_settings", "device_close");
            if (!TGDevice.getInstance().isNetwork(camera)){
                TGToast.showToast(R.string.txt_network_anomaly);
                mSettingItemClose.setChecked(!mSettingItemClose.isChecked());
            }else{
                //1-打开; 0-关闭
                if (mSettingItemClose.isChecked()) {
                    setCloseCMD(1);
                } else {
                    setCloseCMD(0);
                }
            }
        });

        findViewById(R.id.rl_settings_change_device_wifi).setOnClickListener(v -> {
            int  type= RESET_DEVICE_ACTIVITY;
            if (DeviceHelper.isOnline(mDevice)){
                type = CHANGE_DEVICE_WIFI_ACTIVITY;
            }
            int status = DeviceHelper.isOnline(mDevice)? 1 : 0;
            P2PReport.reportCameraStatusOfClickBtn(mDevice.uuid, "device_settings", "changed_device_wifi", status);
            LogUtils.onEventClickByName("device_settings", "changed_device_wifi");

            DeviceSettingHelper.doJump(MoreSettingsActivity.this, type, mDeviceSettingsInfo, mDevice);
        });


        mSettingItemIPConfig.setOnClickListener(v -> {
            if (!TGDevice.getInstance().isNetwork(camera)){
                TGToast.showToast(R.string.txt_network_anomaly);
                return;
            }
            jumpNetworkActivity();
        });
        mSettingItemTimeZone.setOnClickListener(v -> {
            String url = TGGlobalConfigHelper.getInstance().getTimeZoneUrl();
            if (TextUtils.isEmpty(url))return;
            UriUtil.openServePlay(this, url, mDeviceSettingsInfo, 0);
        });
    }

    private boolean showWIFI(){
        if (DeviceHelper.is4GDevice(mDevice) && !DeviceHelper.isCar(mDevice)) {
            return false;
        }
        if (DeviceHelper.isCar(mDevice)) {
            return false;
        }

        if (mDevice != null && DeviceTypeHelper.isBattery(mDevice.attrs)){
            return false;
        }

        if (camera !=  null && camera.isShared){
            return false;
        }

        return !CameraHub.getInstance().isEnableLocalApConnect();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            if (data != null) {
                SMsgAVIoctrlIPCONFIGRespBean sMsgAVIoctrlIPCONFIGRespBean = data.getParcelableExtra(NetworkSettingsActivity.NETWORK_CONFIG);
                if (sMsgAVIoctrlIPCONFIGRespBean != null) {
                    mSMsgAVIoctrlIPCONFIGResp = sMsgAVIoctrlIPCONFIGRespBean;
                    if (mSMsgAVIoctrlIPCONFIGResp.bDhcpEnabled == 0){
                        mSettingItemIPConfig.setContent(R.string.txt_manual_network_setting);
                    }else{
                        mSettingItemIPConfig.setContent(R.string.txt_auto_network_setting);
                    }
                }
            }
        }else if (resultCode==1){
            getDeviceInfo();
        }

    }
    /**
     * 更新设备访问密码
     */
    private void getDeviceInfo() {
        if (mDevice==null)return;
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("device_id", String.valueOf(mDevice.id));
        TGHttp.getInstance().getDevicePassword(hashMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ClientObserver<DeviceItem>() {
                    @Override
                    protected void onSuccess(DeviceItem content) {
                        if (content!=null){
                            mDevice = content;
                        }
                        setTimeZoneText();
                    }
                });
    }

    private void jumpNetworkActivity() {
        Intent intent = new Intent();
        mDeviceSettingsInfo.hasDeviceUpdate = mDevice.is_upgrade == 1;
        mDeviceSettingsInfo.device_type = mDevice.device_type;
        intent.putExtra(EXT_DEVICE_INFO, mDeviceSettingsInfo);
        intent.putExtra(Camera.EXT_UUID, mDevice.uuid);
        if (mDevice.ai_server_data != null) {
            mDeviceSettingsInfo.ai_service = true;
        }
        if (TextUtils.isEmpty(mDeviceSettingsInfo.version)) {
            mDeviceSettingsInfo.version = mDevice.current_version;
        }

        intent.setClass(MoreSettingsActivity.this, NetworkSettingsActivity.class);
        intent.putExtra(CommonConstants.EXT_DEVICE_ITEM, mDevice);
        intent.putExtra(NetworkSettingsActivity.NETWORK_CONFIG, mSMsgAVIoctrlIPCONFIGResp);
        intent.putExtra(DeviceInfoActivity.EXT_DEVICE_NAME_TYPE, DeviceHelper.getDeviceTypeName(mDevice));
        startActivityForResult(intent, 0);
        LogUtils.onEventClickByName("device_settings", "changed_device_wifi");
    }
}